<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="家庭名称" prop="familyId" style="width: 350px;">
        <el-select
            v-model="queryParams.familyId"
            placeholder="请选择家庭"
            clearable
            filterable
            @change="handleFamilyChange"
        >
          <el-option
              v-for="item in familyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="房间名称" prop="roomName" style="width: 350px;">
        <el-select
            v-model="queryParams.roomName"
            placeholder="请选择房间名称"
            clearable
            filterable
        >
          <el-option
              v-for="item in roomOptions"
              :key="item.roomId"
              :label="item.roomName"
              :value="item.roomName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input
            v-model="queryParams.floor"
            placeholder="请输入楼层"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="朝向" prop="orientation">
        <el-input
            v-model="queryParams.orientation"
            placeholder="请输入朝向"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间类型" prop="roomType" style="width: 350px;">
        <el-select v-model="queryParams.roomType" placeholder="请选择房间类型" clearable>
          <el-option
              v-for="dict in air_roomtype"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
                        v-model="queryParams.createdAt"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roomsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
          label="序号"
          align="center"
          width="80"
          class-name="serial-number"
      >
        <template #default="scope">
    <span class="serial">
      {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="家庭名称" align="center" prop="familyId">
        <template #default="scope">
          {{ getFamilyName(scope.row.familyId) }}
        </template>
      </el-table-column>
      <el-table-column label="房间名称" align="center" prop="roomName" />
      <el-table-column label="楼层" align="center" prop="floor" />
      <el-table-column label="朝向" align="center" prop="orientation" />
      <el-table-column label="房间类型" align="center" prop="roomType">
        <template #default="scope">
          <dict-tag :options="air_roomtype" :value="scope.row.roomType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="success" icon="PieChart" @click="handleChart(scope.row)">图表</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roomsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="家庭名称" prop="familyId">
          <el-select
              v-model="form.familyId"
              placeholder="请选择家庭"
              clearable
              filterable
          >
            <el-option
                v-for="item in familyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="朝向" prop="orientation">
          <el-input v-model="form.orientation" placeholder="请输入朝向" />
        </el-form-item>
        <el-form-item label="房间类型" prop="roomType">
          <el-select v-model="form.roomType" placeholder="请选择房间类型">
            <el-option
                v-for="dict in air_roomtype"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="form.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图表对话框 -->
    <el-dialog title="房间数据图表" v-model="chartVisible" width="80%" append-to-body>
      <div class="chart-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-box">
              <h4>房间基本信息</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="房间ID">{{ currentRoom.roomId }}</el-descriptions-item>
                <el-descriptions-item label="房间名称">{{ currentRoom.roomName }}</el-descriptions-item>
                <el-descriptions-item label="楼层">{{ currentRoom.floor }}</el-descriptions-item>
                <el-descriptions-item label="朝向">{{ currentRoom.orientation }}</el-descriptions-item>
                <el-descriptions-item label="房间类型">
                  <dict-tag :options="air_roomtype" :value="currentRoom.roomType"/>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-box">
              <h4>温湿度表</h4>
              <div ref="tempHumidityChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <div class="chart-box">
              <h4>PM颗粒物浓度</h4>
              <div ref="pmChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-box">
              <h4>甲醛浓度</h4>
              <div ref="formaldehydeChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Rooms">
import { listRooms, getRooms, delRooms, addRooms, updateRooms } from "@/api/airsystem/rooms";
import { listFamilies } from "@/api/airsystem/families";
import { listDevices } from "@/api/airsystem/devices";
import { listTemp } from "@/api/airsystem/temp";
import { listPmlevels } from "@/api/airsystem/pmlevels";
import { listFormaldehyde } from "@/api/airsystem/formaldehyde";
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance();
const { air_roomtype } = proxy.useDict('air_roomtype');

const roomsList = ref([]);
const familyOptions = ref([]);
const roomOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const chartVisible = ref(false);
const currentRoom = ref({});
const tempHumidityChart = ref(null);
const pmChart = ref(null);
const formaldehydeChart = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomName: null,
    floor: null,
    orientation: null,
    roomType: null,
    createdAt: null
  },
  rules: {
    familyId: [
      { required: true, message: "家庭ID不能为空", trigger: "blur" }
    ],
    roomName: [
      { required: true, message: "房间名称不能为空", trigger: "blur" }
    ],
    floor: [
      { required: true, message: "楼层不能为空", trigger: "blur" }
    ],
    orientation: [
      { required: true, message: "朝向不能为空", trigger: "blur" }
    ],
    roomType: [
      { required: true, message: "房间类型不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询家庭列表 */
function getFamilyList() {
  listFamilies().then(response => {
    // 确保接口返回数据包含 familyId 和 familyName
    familyOptions.value = response.rows.map(item => ({
      value: item.familyId, // 保持提交值为 familyId
      label: item.familyName // 显示家庭名称
    }));
  });
}

// 根据 familyId 获取家庭名称
const getFamilyName = (familyId) => {
  const family = familyOptions.value.find(item => item.value === familyId);
  return family ? family.label : '未知家庭';
};

// 根据 familyId 获取房间列表
async function getRoomListByFamily(familyId) {
  if (!familyId) {
    roomOptions.value = [];
    queryParams.value.roomName = null;
    return;
  }

  try {
    const response = await listRooms({ familyId: familyId });
    roomOptions.value = response.rows || [];
    queryParams.value.roomName = null; // 清空房间名称选择
  } catch (error) {
    proxy.$modal.msgError("获取房间列表失败");
    console.error("获取房间列表失败:", error);
  }
}

/** 查询房间管理列表 */
function getList() {
  loading.value = true;
  listRooms(queryParams.value).then(response => {
    roomsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    roomId: null,
    familyId: null,
    roomName: null,
    floor: null,
    orientation: null,
    roomType: null,
    createdAt: null
  };
  proxy.resetForm("roomsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roomId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加房间管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _roomId = row.roomId || ids.value;
  getRooms(_roomId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改房间管理";
  });
}

/** 图表按钮操作 */
async function handleChart(row) {
  currentRoom.value = row;
  chartVisible.value = true;

  try {
    // 1. 获取该房间下的所有设备
    const devicesRes = await listDevices({ roomId: row.roomId });
    const devices = devicesRes.rows || [];

    if (devices.length === 0) {
      proxy.$modal.msgWarning("该房间下没有设备");
      return;
    }

    // 2. 获取所有设备的所有数据
    const tempRecords = [];
    const pmRecords = [];
    const formaldehydeRecords = [];

    // 遍历设备，根据设备类型获取所有数据
    for (const device of devices) {
      if (device.deviceName === "0") {
        // 温湿度设备 - 获取所有数据
        const res = await listTemp({ deviceId: device.deviceId });
        tempRecords.push(...res.rows);
      } else if (device.deviceName === "2") {
        // PM设备 - 获取所有数据
        const res = await listPmlevels({ deviceId: device.deviceId });
        pmRecords.push(...res.rows);
      } else if (device.deviceName === "4") {
        // 甲醛设备 - 获取所有数据
        const res = await listFormaldehyde({ deviceId: device.deviceId });
        formaldehydeRecords.push(...res.rows);
      }
    }

    // 3. 按时间排序并取最后5条记录
    const getLastFiveRecords = (records) => {
      return records
          .sort((a, b) => new Date(a.recordTime) - new Date(b.recordTime))
          .slice(-5);
    };

    const lastFiveTempRecords = getLastFiveRecords(tempRecords);
    const lastFivePmRecords = getLastFiveRecords(pmRecords);
    const lastFiveFormaldehydeRecords = getLastFiveRecords(formaldehydeRecords);

    // 4. 初始化图表
    nextTick(() => {
      initTempHumidityChart(lastFiveTempRecords);
      initPmChart(lastFivePmRecords);
      initFormaldehydeChart(lastFiveFormaldehydeRecords);
    });

  } catch (error) {
    proxy.$modal.msgError("获取设备数据失败");
    console.error("获取设备数据失败:", error);
  }
}

/** 初始化温湿度图表 */
function initTempHumidityChart(records) {
  if (!tempHumidityChart.value) return;

  const chart = echarts.init(tempHumidityChart.value);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['温度', '湿度']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: records.map(r => formatDate(r.recordTime))
    },
    yAxis: [
      {
        type: 'value',
        name: '温度',
        min: 15,
        max: 30,
        position: 'left',
        axisLabel: {
          formatter: '{value} °C'
        }
      },
      {
        type: 'value',
        name: '湿度',
        min: 30,
        max: 80,
        position: 'right',
        axisLabel: {
          formatter: '{value} %'
        }
      }
    ],
    series: [
      {
        name: '温度',
        type: 'line',
        yAxisIndex: 0,
        data: records.map(r => r.temperature),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#f56c6c'
        },
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '湿度',
        type: 'line',
        yAxisIndex: 1,
        data: records.map(r => r.humidity),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409eff'
        },
        itemStyle: {
          color: '#409eff'
        }
      }
    ]
  };
  chart.setOption(option);
}

/** 初始化PM图表 */
function initPmChart(records) {
  if (!pmChart.value) return;

  const chart = echarts.init(pmChart.value);

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['PM2.5', 'PM10']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: records.map(r => formatDate(r.recordTime))
    },
    yAxis: {
      type: 'value',
      name: '浓度(μg/m³)',
      min: 0,
      max: 200
    },
    series: [
      {
        name: 'PM2.5',
        type: 'line',
        data: records.map(r => r.pm25),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#67c23a'
        },
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: 'PM10',
        type: 'line',
        data: records.map(r => r.pm10),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#e6a23c'
        },
        itemStyle: {
          color: '#e6a23c'
        }
      }
    ]
  };
  chart.setOption(option);
}

/** 初始化甲醛浓度图表 */
function initFormaldehydeChart(records) {
  if (!formaldehydeChart.value) return;

  const chart = echarts.init(formaldehydeChart.value);

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: records.map(r => formatDate(r.recordTime))
    },
    yAxis: {
      type: 'value',
      name: '浓度(mg/m³)',
      min: 10,
      max: 100
    },
    series: [
      {
        name: '甲醛浓度',
        type: 'line',
        data: records.map(r => r.formaldehydeLevel),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#909399'
        },
        itemStyle: {
          color: '#909399'
        }
      }
    ]
  };
  chart.setOption(option);
}

/** 格式化日期显示 */
function formatDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getMonth()+1}/${date.getDate()}`;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roomsRef"].validate(valid => {
    if (valid) {
      if (form.value.roomId != null) {
        updateRooms(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRooms(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _roomIds = row.roomId || ids.value;
  proxy.$modal.confirm('是否确认删除房间管理编号为"' + _roomIds + '"的数据项？').then(function() {
    return delRooms(_roomIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 家庭选择变化时触发
function handleFamilyChange(familyId) {
  getRoomListByFamily(familyId);
}

// 组件挂载时获取家庭列表
onMounted(() => {
  getFamilyList();
});

getList();
</script>

<style scoped>
.chart-container {
  padding: 20px;
}

.chart-box {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table th.el-table__cell.is-leaf {
  text-align: center;
}
</style>



